/**
 * 
 */
package com.panshi.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

/**
 * @author wmk
 *
 */
@Configuration
public class MySpringCacheConfig {
	//private Duration timeToLive = Duration.ZERO;
	//public void setTimeToLive(Duration timeToLive) {
		//this.timeToLive = timeToLive;
//	}
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		RedisTemplate<String, Object> template = new RedisTemplate();
		//配置具体的序列化
		template.setConnectionFactory(redisConnectionFactory);

		//Json序列化配置
		Jackson2JsonRedisSerializer Jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper om=new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		Jackson2JsonRedisSerializer.setObjectMapper(om);
		//String 的序列化
		StringRedisSerializer StringRedisSerializer = new StringRedisSerializer();
		//key采用String的序列化方式
		template.setKeySerializer(StringRedisSerializer);
		//hash的key也采用String的序列化方式
		template.setHashKeySerializer(StringRedisSerializer);
		//value序列化方式采用jackson
		template.setValueSerializer(Jackson2JsonRedisSerializer);
		//hash的value序列化方式采用jackson
		template.setHashKeySerializer(Jackson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}


	@Bean
	public RedisCacheConfiguration redisCacheConfiguration() {
		//只有fastjson稳定
		RedisSerializer<?> valSeri=new GenericFastJsonRedisSerializer();
		return RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valSeri));
	}

}
